﻿using OPCDa;
using OpcSelfHost.basePage;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace OpcSelfHost.printer
{
    public class ZtAutoPrint
    {
        public string Ip { get; set; }

        public Dictionary<string, string> tem ;

        private bool boolIsCon = false ;

        private string[] ConfigTags = { "tagPrint", "tagBarrelWET", "tagBarrelNO", "tagGrossWet", "tagNetWet", "tagBATCHNO" , "tagProductdate" , "tagEXP" };

        public void Start()
        {

            ///开启任务  
            CancellationTokenSource tokenSource_plcsend = new CancellationTokenSource();
            CancellationToken token_plcsend = tokenSource_plcsend.Token;

            //定时服务，判断opc是否启动成功 
            Task task = new Task(async () =>
            { 
                while (true)
                {
                    if (token_plcsend.IsCancellationRequested)
                    {
                        return;
                    }

                    if (boolIsCon)
                    {
                        return;
                    }
                    runprint();

                    await Task.Delay(3 * 1000);
                }

            }, token_plcsend);
            task.Start();


        }


        private void runprint()
        {

            string[] tags = new string[ConfigTags.Length];
            for (int i = 0; i < ConfigTags.Length; i++)
            {
                tags[i] = CommonBase.ConfigGetValue(ConfigTags[i]);
            }

            try
            {

                OPCHelper OPCHelper = new OPCHelper(CommonBase.serverip, CommonBase.servername, 1);
                if (OPCHelper.Connected)
                {
                    boolIsCon = true;
                    OPCHelper.AddItems(tags);

                    var goodTags = OPCHelper.itemNames.ToArray();
                    Array values = OPCHelper.Read(goodTags);

                    Dictionary<string, object> dic_return = new Dictionary<string, object>();

                    for (int i = 0; i < goodTags.Length; i++)
                    {
                        if (!dic_return.ContainsKey(goodTags[i]))
                        {
                            dic_return.Add(goodTags[i], values.GetValue(i + 1));
                        }

                    }


                 

                    tem = new Dictionary<string, string>();
                    tem.Add("Produced", DateTime.Now.ToString("yyyy-MM-dd"));
                    tem.Add("Expired", DateTime.Now.AddYears(-1).ToString("yyyy-MM-dd"));
                    for (int i = 0; i < tags.Length; i++)
                    {
                        tem.Add(ConfigTags[i], dic_return.ContainsKey(tags[i]) ? dic_return[tags[i]].ToString() : "");
                    }


                    ///开启任务  
                    CancellationTokenSource tokenSource_plcsend = new CancellationTokenSource();
                    CancellationToken token_plcsend = tokenSource_plcsend.Token;

                    //定时服务，判断opc是否启动成功 
                    Task task = new Task(async () =>
                    {
                        //await Task.Delay(SendConfig.read_sec * 1000);
                        while (true)
                        {
                            if (token_plcsend.IsCancellationRequested)
                            {
                                return;
                            }

                            //检测到信号位为1 
                            string signTag = CommonBase.ConfigGetValue("tagPrint");
                            //读取点位
                            string signvalue =  OPCHelper.Read(new string[] { signTag }).GetValue(1).ToString();
                            if (signvalue == "1")
                            {
                                 
                                SocketClient sc = new SocketClient();
                                sc.setIpAndPort(Ip, 9100);
                                if (sc.ConnetToServices())
                                {
                                     sc.WriteFile(Encoding.Default.GetBytes(temfile("nb.txt")));
                                    sc.WriteFile(Encoding.Default.GetBytes(temfile("wb.txt")));
                                    sc.CloseConnection();
                                }
                                //重置信号

                                OPCHelper.AsyncWrite(new string[] { signTag }, new string[] { "0" });
                            }

                            await Task.Delay(3 * 1000);
                        }

                    }, token_plcsend);
                    task.Start();



                }
                else
                {

                }


            }
            catch (Exception ex)
            {

            }

        }

        public bool Check()
        {
            bool re = false;
            SocketClient sc = new SocketClient();
            sc.setIpAndPort(Ip, 9100);
            if (sc.ConnetToServices())
            {
                re = true;
                sc.CloseConnection();
            }
            return re; ;
        }


         


        private string temfile(string file)
        {
            string str = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "Config/"+ file);
            

            // private string[] ConfigTags = { "tagPrint", "tagBarrelWET", "tagBarrelNO", "tagGrossWet", "tagNetWet", "tagBATCHNO" };

            decimal neta = tem.ContainsKey("tagNetWet") ? Convert.ToDecimal(tem["tagNetWet"]) : 0; //净重
            decimal GrossWet = tem.ContainsKey("tagGrossWet") ? Convert.ToDecimal(tem["tagGrossWet"]) : 0; //皮重
            decimal BarrelWET = tem.ContainsKey("tagBarrelWET") ? Convert.ToDecimal(tem["tagBarrelWET"]) : 0; //桶重

            str = str.Replace("{{.tagNbGrossWet}}", Math.Round( neta + GrossWet,2).ToString("#0.00"));
            str = str.Replace("{{.tagWbGrossWet}}", Math.Round(neta + GrossWet + BarrelWET, 2).ToString("#0.00"));
            str = str.Replace("{{.tagNetWet}}", Math.Round(neta, 2).ToString("#0.00"));

            foreach (KeyValuePair<string, string> kvp in tem)
            {
                str = str.Replace("{{." + kvp.Key + "}}", kvp.Value);
            }

            return str;
        }





        }
}
